/*
 * monarch.cpp
 *
 *  Created on: Dec 14, 2010
 *      Author: dt
 */


/*
 * Jingle call example
 * Copyright 2004--2005, Google Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Tempe Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <iomanip>
#include <time.h>

#ifndef WIN32
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iomanip>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#else
#include <direct.h>
//typedef _getcwd getcwd;
#include "talk/base/win32.h"
#endif


#ifdef OSX
#include "talk/base/macsocketserver.h"
#endif

#include "monarchController.h"




class DebugLog : public sigslot::has_slots<> {
public:
  DebugLog() :
    debug_input_buf_(NULL), debug_input_len_(0), debug_input_alloc_(0),
    debug_output_buf_(NULL), debug_output_len_(0), debug_output_alloc_(0),
    censor_password_(false)
      {}
  char * debug_input_buf_;
  int debug_input_len_;
  int debug_input_alloc_;
  char * debug_output_buf_;
  int debug_output_len_;
  int debug_output_alloc_;
  bool censor_password_;

  void Input(const char * data, int len) {
    if (debug_input_len_ + len > debug_input_alloc_) {
      char * old_buf = debug_input_buf_;
      debug_input_alloc_ = 4096;
      while (debug_input_alloc_ < debug_input_len_ + len) {
        debug_input_alloc_ *= 2;
      }
      debug_input_buf_ = new char[debug_input_alloc_];
      memcpy(debug_input_buf_, old_buf, debug_input_len_);
      delete[] old_buf;
    }
    memcpy(debug_input_buf_ + debug_input_len_, data, len);
    debug_input_len_ += len;
    DebugPrint(debug_input_buf_, &debug_input_len_, false);
  }

  void Output(const char * data, int len) {
    if (debug_output_len_ + len > debug_output_alloc_) {
      char * old_buf = debug_output_buf_;
      debug_output_alloc_ = 4096;
      while (debug_output_alloc_ < debug_output_len_ + len) {
        debug_output_alloc_ *= 2;
      }
      debug_output_buf_ = new char[debug_output_alloc_];
      memcpy(debug_output_buf_, old_buf, debug_output_len_);
      delete[] old_buf;
    }
    memcpy(debug_output_buf_ + debug_output_len_, data, len);
    debug_output_len_ += len;
    DebugPrint(debug_output_buf_, &debug_output_len_, true);
  }

  static bool
  IsAuthTag(const char * str, size_t len) {
    if (str[0] == '<' && str[1] == 'a' &&
                         str[2] == 'u' &&
                         str[3] == 't' &&
                         str[4] == 'h' &&
                         str[5] <= ' ') {
      std::string tag(str, len);

      if (tag.find("mechanism") != std::string::npos)
        return true;

    }
    return false;
  }

  void
  DebugPrint(char * buf, int * plen, bool output) {
    int len = *plen;
    if (len > 0) {
      time_t tim = time(NULL);
      struct tm * now = localtime(&tim);
      char *time_string = asctime(now);
      if (time_string) {
        size_t time_len = strlen(time_string);
        if (time_len > 0) {
          time_string[time_len-1] = 0;    // trim off terminating \n
        }
      }
      LOG(INFO) << (output ? "SEND >>>>>>>>>>>>>>>>>>>>>>>>>" : "RECV <<<<<<<<<<<<<<<<<<<<<<<<<")
        << " : " << time_string;

      bool indent;
      int start = 0, nest = 3;
      for (int i = 0; i < len; i += 1) {
        if (buf[i] == '>') {
          if ((i > 0) && (buf[i-1] == '/')) {
            indent = false;
          } else if ((start + 1 < len) && (buf[start + 1] == '/')) {
            indent = false;
            nest -= 2;
          } else {
            indent = true;
          }

          // Output a tag
          LOG(INFO) << std::setw(nest) << " " << std::string(buf + start, i + 1 - start);

          if (indent)
            nest += 2;

          // Note if it's a PLAIN auth tag
          if (IsAuthTag(buf + start, i + 1 - start)) {
            censor_password_ = true;
          }

          // incr
          start = i + 1;
        }

        if (buf[i] == '<' && start < i) {
          if (censor_password_) {
            LOG(INFO) << std::setw(nest) << " " << "## TEXT REMOVED ##";
            censor_password_ = false;
          }
          else {
            LOG(INFO) << std::setw(nest) << " " << std::string(buf + start, i - start);
          }
          start = i;
        }
      }
      len = len - start;
      memcpy(buf, buf + start, len);
      *plen = len;
    }
  }

};

static DebugLog debug_log_;

static const int DEFAULT_PORT = 5222;

static std::string CLIENT_TYPE = "monarch";

void MonarchController::printRoster()
{
  pipe_client_->PrintRoster();
}


bool MonarchController::requestTunnelTo(std::string& user, ConnectionCallback *conn)
{
  return pipe_client_->ConnectTo(user,conn);

}


MonarchController::MonarchController(XMPPCallback *xmppCallback,  std::string& username, std::string& password,  std::string& xmppServerAddress, bool& debug, cricket::MediaEngine* mediaEngine)
:xmppCallback_(xmppCallback), username_(username), password_(password), server_(xmppServerAddress), debug_(debug), media_engine_(mediaEngine)
{

   // parse username and password, if present
   buzz::Jid jid;
   talk_base::InsecureCryptStringImpl pass;
   pass.password() = password_;


   if (debug)
     talk_base::LogMessage::LogToDebug(talk_base::LS_VERBOSE);
   else
     talk_base::LogMessage::LogToDebug(talk_base::LS_ERROR + 1);


   if (username.find('@') == std::string::npos)
     {
       username.append("@localhost");
     }
   jid = buzz::Jid(username);
   if (!jid.IsValid() || jid.node() == "")
     {
       printf("Invalid JID. JIDs should be in the form user@domain\n");
      // return 1;
     }
//   if (pass.password().empty() && !test_server)
   if (pass.password().empty() )
     {
       printf("Empty Password not Allowed.\n");
     }

   xcs_ = new buzz::XmppClientSettings();
   xcs_->set_user(jid.node());
   xcs_->set_resource(CLIENT_TYPE);
   xcs_->set_host(jid.domain());

   xcs_->set_pass(talk_base::CryptString(pass));

   /*
   xcs_->set_use_tls(!test_server);
   if (plain_server) {
     xcs_->set_use_tls(false);
     xcs_->set_allow_plain(true);
   }
   if (test_server) {
     pass.password() = jid.node();
     xcs_->set_allow_plain(true);
   }
*/


   std::string host;
   int port;

   int colon = server_.find(':');
   if (colon == -1)
     {
       host = server_;
       port = DEFAULT_PORT;
     }
   else
     {
       host = server_.substr(0, colon);
       port = atoi(server_.substr(colon + 1).c_str());
     }

   xcs_->set_server(talk_base::SocketAddress(host, port));

  talk_base::InitializeSSL();

  printf("Controller created as %s as %s\n", server_.c_str(), jid.Str().c_str());
}





void MonarchController::start()
{

  XmppPump pump;

  //talk_base::PhysicalSocketServer ss;
#if WIN32
  // Need to pump messages on our main thread on Windows.
  talk_base::Win32Thread w32_thread;
  talk_base::ThreadManager::SetCurrent(&w32_thread);
#endif
  talk_base::Thread* main_thread_ = talk_base::Thread::Current();
#ifdef OSX
  talk_base::MacCarbonAppSocketServer ss;
  talk_base::SocketServerScope ss_scope(&ss);
#endif


  if (debug_) {
    pump.client()->SignalLogInput.connect(&debug_log_, &DebugLog::Input);
    pump.client()->SignalLogOutput.connect(&debug_log_, &DebugLog::Output);
  }

  pipe_client_ = new PipeClient(pump.client(), xmppCallback_,media_engine_);

  Console *console = new Console(main_thread_, pipe_client_);
  console->Start();

  pump.DoLogin(*xcs_, new XmppSocket(true), NULL);
  main_thread_->Run();
  pump.DoDisconnect();

  console->Stop();
  delete console;
  delete  pipe_client_;
  //return 0;
}

MonarchController::~MonarchController()
{
//  pump.DoDisconnect();

  //return 0;
  // TODO Auto-generated destructor stub
}



